from django import template
from django.conf import settings
import os.path

register = template.Library()

@register.filter
def get_avatar_url(user):
    """
    Return the user's avatar URL if it exists, otherwise return the default avatar URL.
    """
    try:
        if user.avatar and hasattr(user.avatar, 'url') and os.path.exists(user.avatar.path):
            return user.avatar.url
        return settings.STATIC_URL + 'images/default_avatar.png'
    except Exception:
        return settings.STATIC_URL + 'images/default_avatar.png'

@register.simple_tag
def safe_avatar(user, default_path='admin/img/tx.png', size=None):
    """
    Safely return the HTML img tag for a user avatar.
    If the user has no avatar, or if there's an error accessing it, return the default avatar.
    
    Usage: {% safe_avatar user [default_path] [size] %}
    Example: {% safe_avatar user 'admin/img/tx.png' '40x40' %}
    """
    default_url = settings.STATIC_URL + default_path
    width, height = (40, 40)
    
    if size:
        try:
            if 'x' in size:
                width, height = size.split('x')
            else:
                width = height = size
        except:
            pass
    
    try:
        if user.profile and user.profile.avatar and hasattr(user.profile.avatar, 'url'):
            try:
                if os.path.exists(user.profile.avatar.path):
                    return f'<img src="{user.profile.avatar.url}" alt="{user.username}" class="rounded-circle" width="{width}" height="{height}" style="object-fit: cover;">'
            except:
                pass
    except:
        pass
    
    return f'<img src="{default_url}" alt="默认头像" class="rounded-circle" width="{width}" height="{height}" style="object-fit: cover;">' 